package com.sunlands.qdcy.tongzhuo.web;

import com.sunlands.qdcy.tongzhuo.common.annotation.AuthSig;
import com.sunlands.qdcy.tongzhuo.common.annotation.AutoLog;
import com.sunlands.qdcy.tongzhuo.constant.CommonResultMessage;
import com.sunlands.qdcy.tongzhuo.exception.SensitiveException;
import com.sunlands.qdcy.tongzhuo.feign.SocketClient;
import com.sunlands.qdcy.tongzhuo.feign.vo.UserInfoDTO;
import com.sunlands.qdcy.tongzhuo.model.DiaryDO;
import com.sunlands.qdcy.tongzhuo.model.UserDiaryReplyDO;
import com.sunlands.qdcy.tongzhuo.model.UserDiaryZanDO;
import com.sunlands.qdcy.tongzhuo.service.DiaryService;
import com.sunlands.qdcy.tongzhuo.service.InteractionMessageService;
import com.sunlands.qdcy.tongzhuo.service.UserDiaryReplyService;
import com.sunlands.qdcy.tongzhuo.service.UserDiaryZanService;
import com.sunlands.qdcy.tongzhuo.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import static com.sunlands.qdcy.tongzhuo.common.annotation.AutoLog.Level.DEBUG;
import static com.sunlands.qdcy.tongzhuo.constant.CommonResultMessage.CON_SENSITIVE;

/**
 * 评论回复
 *
 * @author gaoyanfeng
 *  2019-06-14 16:56
 **/
@RestController
@Slf4j
@RequestMapping("/user/reply")
@Api(tags = "4、评论回复相关")
public class UserReplyController extends BaseController {

    @Autowired
    private UserDiaryReplyService userDiaryReplyService;
    @Autowired
    private DiaryService userDiaryService;
    @Autowired
    private UserDiaryZanService userDiaryZanService;
    @Autowired
    private InteractionMessageService interactionMessageService;
    @Autowired
    private SocketClient socketClient;

    @ApiOperation(value = "删除回复,前端调用", notes = "删除回复")
    @PostMapping("/delete/reply")
    @AuthSig
    public BusinessResult deleteReply(@ApiParam(value = "回复id", required = true) @RequestParam Long id) {
        if (null == id) {
            return BusinessResult.createInstance(CommonResultMessage.PARMAS_INVALID);
        }
        try {
            userDiaryReplyService.deleteReplyById(id);
        } catch (Exception e) {
            log.error("未知错误：e={}", e);
            return BusinessResult.createInstance(CommonResultMessage.DIARY_FAIL);
        }
        return BusinessResult.createSuccessInstance("ok");
    }

    @ApiOperation(value = "评论详情,前端调用", notes = "评论详情", response = UserDiaryCommentVO.class)
    @GetMapping("/detail")
    @AuthSig
    public BusinessResult commentDetail(@ApiParam(value = "评论id", required = true) @RequestParam Long id,
                                        @ApiParam(value = "用户id", required = true) @RequestParam Long userId,
                                        @ApiParam(value = "页码", required = true) @RequestParam(defaultValue = "1") Integer page,
                                        @ApiParam(value = "页码大小", required = true) @RequestParam(defaultValue = "4") Integer size) {
        if (null == id || page < 1 || size < 1) {
            return BusinessResult.createInstance(CommonResultMessage.PARMAS_INVALID);
        }
        UserDiaryCommentVO userDiaryComment;
        try {
            Future<UserDiaryCommentVO> future = userDiaryReplyService.pageByComentId(id, userId, page, size);
            userDiaryComment = future.get(10, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("", e);
            return BusinessResult.createInstance(CommonResultMessage.DIARY_FAIL);
        }
        return BusinessResult.createSuccessInstance(userDiaryComment);
    }

    @ApiOperation(value = "消息-回复列表,前端调用", notes = "消息回复列表")
    @GetMapping("/page/message")
    @AuthSig
    public BusinessResult messageReplyPage(@ApiParam(value = "用户id", required = true) @RequestParam Long userId,
                                           @ApiParam(value = "页码", required = true) @RequestParam(defaultValue = "1") Integer page,
                                           @ApiParam(value = "页码大小", required = true) @RequestParam(defaultValue = "4") Integer size) {
        if (null == userId || page < 1 || size < 1) {
            return BusinessResult.createInstance(CommonResultMessage.PARMAS_INVALID);
        }
        try {
            userId = currentUserId();
            if (null == userId) {
                return BusinessResult.createInstance(CommonResultMessage.USER_NOT_LOGIN);
            }
            Page<MessageReplyVO> messageReplyVOList = interactionMessageService.messagePageByUserId(userId, page, size);
            return BusinessResult.createSuccessInstance(messageReplyVOList);
        } catch (Exception e) {
            log.error("未知错误：e= {}", e);
            return BusinessResult.createInstance(CommonResultMessage.DIARY_FAIL);
        }
    }

    @ApiOperation(value = "新增回复,前端调用", notes = "新增回复", response = UserDiaryListVO.class)
    @PostMapping("/add/reply")
    @AuthSig
    public BusinessResult addReply(@ApiParam(value = "回复", required = true) @RequestBody UserDiaryReplyDO userDiaryReply) {
        String checkAddReply = checkAddReply(userDiaryReply);
        if (null != checkAddReply) {
            return BusinessResult.createInstance(CommonResultMessage.PARMAS_INVALID, checkAddReply);
        }

        //敏感词校验
        BusinessResult checkContent = socketClient.checkContent(CheckVO.builder().content(userDiaryReply.getReplyContent()).build());
        if (checkContent.getCode().equals(CON_SENSITIVE.code)) {
            throw new SensitiveException("回复内容： " + userDiaryReply.getReplyContent()+ "\n敏感词：" +checkContent.getMessage());
        }

        Long userId = userDiaryReply.getReplyUserId();
        Long replyedId = userDiaryReply.getReplyedId();
        Long replyedUserId = userDiaryReply.getReplyedUserId();
        Long diaryId = null;
        try {
            UserInfoDTO userInfoDTO = getByUserId(userId);
            if (userInfoDTO == null) {
                return BusinessResult.createInstance(CommonResultMessage.USER_INVALID);
            }
            userDiaryReply.setReplyUserId(userId);
            if (UserDiaryReplyDO.TypeEnums.REPLY_COMMENT == UserDiaryReplyDO.TypeEnums.create(userDiaryReply.getType()) ||
                    UserDiaryReplyDO.TypeEnums.REPLY_REPLY == UserDiaryReplyDO.TypeEnums.create(userDiaryReply.getType())) {
                UserDiaryReplyDO byReplyId = userDiaryReplyService.getByReplyId(replyedId);
                if (null == byReplyId) {
                    return BusinessResult.createInstance(CommonResultMessage.REPLAY_NOT_EXIST);
                }
                userDiaryReply.setCommentId(byReplyId.getCommentId());
                diaryId = byReplyId.getDiaryId();
                replyedUserId = byReplyId.getReplyUserId();
            } else if (UserDiaryReplyDO.TypeEnums.DIARY_COMMENT == UserDiaryReplyDO.TypeEnums.create(userDiaryReply.getType())) {
                DiaryDO byDiaryId = userDiaryService.findById(replyedId);
                if (null == byDiaryId) {
                    return BusinessResult.createInstance(CommonResultMessage.DIARY_NOT_EXIST);
                }
                diaryId = byDiaryId.getId();
                replyedUserId = byDiaryId.getUserId();
            }
            try {
                userDiaryReply.setDiaryId(diaryId);
                userDiaryReply.setReplyedUserId(replyedUserId);
                UserDiaryListVO userDiaryList = userDiaryReplyService.addReply(userDiaryReply);
                return BusinessResult.createSuccessInstance(userDiaryList);
            } catch (Exception ex) {
                log.error("user comment reply error ,ex = {}", ex);
                return BusinessResult.createInstance(CommonResultMessage.DIARY_FAIL);
            }
        } catch (Exception e) {
            log.error("", e);
            return BusinessResult.createInstance(CommonResultMessage.DIARY_FAIL);
        }
    }

    @AutoLog
    @ApiOperation(value = "新增回复,移动端调用", notes = "新增回复，移动端", response = UserDiaryListVO.class)
    @PostMapping("/mobile/add/reply")
    @AuthSig
    public BusinessResult addMobileReply(@ApiParam(value = "回复", required = true) @RequestBody UserDiaryReplyDO userDiaryReply) {
        String checkAddReply = checkAddReply(userDiaryReply);
        if (null != checkAddReply) {
            return BusinessResult.createInstance(CommonResultMessage.PARMAS_INVALID.getCode(), checkAddReply, null);
        }

        //敏感词校验
        BusinessResult checkContent = socketClient.checkContent(CheckVO.builder().content(userDiaryReply.getReplyContent()).build());
        if (checkContent.getCode().equals(CON_SENSITIVE.code)) {
            throw new SensitiveException("回复内容： " + userDiaryReply.getReplyContent()+ "\n敏感词：" +checkContent.getMessage());
        }

        Long userId = userDiaryReply.getReplyUserId();
        Long replyedId = userDiaryReply.getReplyedId();
        Long replyedUserId = userDiaryReply.getReplyedUserId();
        Long diaryId = null;
        try {
            UserInfoDTO userInfoDTO = getByUserId(userId);
            if (userInfoDTO == null) {
                return BusinessResult.createInstance(CommonResultMessage.USER_INVALID);
            }
            userDiaryReply.setReplyUserId(userId);
            if (UserDiaryReplyDO.TypeEnums.REPLY_COMMENT == UserDiaryReplyDO.TypeEnums.create(userDiaryReply.getType()) ||
                    UserDiaryReplyDO.TypeEnums.REPLY_REPLY == UserDiaryReplyDO.TypeEnums.create(userDiaryReply.getType())) {
                UserDiaryReplyDO byReplyId = userDiaryReplyService.getByReplyId(replyedId);
                if (null == byReplyId) {
                    return BusinessResult.createInstance(CommonResultMessage.REPLAY_NOT_EXIST);
                }
                userDiaryReply.setCommentId(byReplyId.getCommentId());
                diaryId = byReplyId.getDiaryId();
                replyedUserId = byReplyId.getReplyUserId();
            } else if (UserDiaryReplyDO.TypeEnums.DIARY_COMMENT == UserDiaryReplyDO.TypeEnums.create(userDiaryReply.getType())) {
                DiaryDO byDiaryId = userDiaryService.findById(replyedId);
                if (null == byDiaryId) {
                    return BusinessResult.createInstance(CommonResultMessage.DIARY_NOT_EXIST);
                }
                diaryId = byDiaryId.getId();
                replyedUserId = byDiaryId.getUserId();
            }
            try {
                userDiaryReply.setDiaryId(diaryId);
                userDiaryReply.setReplyedUserId(replyedUserId);
                UserDiaryListVO userDiaryList = userDiaryReplyService.addReply(userDiaryReply);
                return BusinessResult.createSuccessInstance(userDiaryList);
            } catch (Exception ex) {
                log.error("user comment reply error ,ex = {}", ex);
                return BusinessResult.createInstance(CommonResultMessage.DIARY_FAIL);
            }
        } catch (Exception e) {
            log.error("新增回复异常 e={}", e);
            return BusinessResult.createInstance(CommonResultMessage.DIARY_FAIL);
        }
    }

    @AutoLog
    @ApiOperation(value = "日记，评论，回复 的 点赞,前端调用", notes = "点赞")
    @PostMapping("/like")
    @AuthSig
    public BusinessResult like(@ApiParam(value = "点赞VO", required = true) @RequestBody UserDiaryZanDO userDiaryZan) {

        String checkAddZan = checkAddZan(userDiaryZan);
        if (null != checkAddZan) {
            return BusinessResult.createInstance(CommonResultMessage.PARMAS_INVALID, checkAddZan);
        }
        UserInfoDTO userInfoDTO = currentUser();
        if (null == userInfoDTO) {
            return BusinessResult.createInstance(CommonResultMessage.USER_INVALID);
        }
        Long currentUserId = userInfoDTO.getId();
        userDiaryZan.setZanUserId(currentUserId);

        if (UserDiaryZanDO.TypeEnums.DIARY == UserDiaryZanDO.TypeEnums.create(userDiaryZan.getType())) {
            DiaryDO userDiary = userDiaryService.findById(userDiaryZan.getTargetId());
            if (null == userDiary) {
                return BusinessResult.createInstance(CommonResultMessage.DIARY_NOT_EXIST);
            }
            UserDiaryZanDO userCommentZanOld = userDiaryZanService.getByTargetIdAndTypeAndUserId(userDiaryZan.getTargetId(), userDiaryZan.getType(), userDiaryZan.getZanUserId());
            if (null != userCommentZanOld) {
                return BusinessResult.createInstance(CommonResultMessage.LIKE_AGAIN);
            }
            userDiaryZan.setZanedUserId(userDiary.getUserId());
        } else if (UserDiaryZanDO.TypeEnums.REPLY == UserDiaryZanDO.TypeEnums.create(userDiaryZan.getType())) {
            UserDiaryReplyDO userDiaryReply = userDiaryReplyService.getByReplyId(userDiaryZan.getTargetId());
            if (null == userDiaryReply) {
                return BusinessResult.createInstance(CommonResultMessage.REPLAY_NOT_EXIST);
            }
            UserDiaryZanDO userReplyZanOld = userDiaryZanService.getByTargetIdAndTypeAndUserId(userDiaryReply.getId(), userDiaryZan.getType(), userDiaryZan.getZanUserId());
            if (null != userReplyZanOld) {
                return BusinessResult.createInstance(CommonResultMessage.LIKE_AGAIN);
            }
            userDiaryZan.setZanedUserId(userDiaryReply.getReplyUserId());
        }
        try {
            userDiaryZanService.addUserDiaryZan(userDiaryZan, userInfoDTO.getName());
        } catch (Exception ex) {
            log.error("user reply zan error ,ex = {}", ex);
            return BusinessResult.createInstance(CommonResultMessage.DIARY_FAIL);
        }
        return BusinessResult.createSuccessInstance(null);
    }

    @AutoLog
    @ApiOperation(value = "日记，评论，回复取消点赞,前端调用", notes = "取消点赞")
    @PostMapping("/notlike")
    @AuthSig
    public BusinessResult notLike(@ApiParam(value = "点赞VO", required = true) @RequestBody UserDiaryZanDO userDiaryZan) {

        Integer type = userDiaryZan.getType();
        Long targetId = userDiaryZan.getTargetId();
        if (null == UserDiaryZanDO.TypeEnums.create(type) || null == userDiaryZan.getTargetId()) {
            return BusinessResult.createInstance(CommonResultMessage.PARMAS_INVALID, "取消点赞类型错误");
        }
        Long userId = currentUserId();
        if (null == userId) {
            return BusinessResult.createInstance(CommonResultMessage.USER_NOT_LOGIN);
        }

        UserDiaryZanDO userCommentZanOld = userDiaryZanService.getByTargetIdAndTypeAndUserId(targetId, type, userId);
        if (null == userCommentZanOld) {
            return BusinessResult.createInstance(CommonResultMessage.LIKE_NOT_EXIST);
        }
        try {
            userDiaryZanService.deleteZanById(userCommentZanOld.getId(), userCommentZanOld.getTargetId(), userCommentZanOld.getType(), userId);
        } catch (Exception ex) {
            log.error("", ex);
            return BusinessResult.createInstance(CommonResultMessage.DIARY_FAIL);
        }
        return BusinessResult.createSuccessInstance(null);
    }

    @AutoLog(logLevel = DEBUG)
    @ApiOperation(value = "消息-点赞列表,前端调用", notes = "消息点赞列表")
    @GetMapping("/likeList")
    @AuthSig
    public BusinessResult<Page<UserDiaryZanVO>> zanList(@ApiParam(value = "用户id", required = true) @RequestParam Long userId,
                                                        @ApiParam(value = "页码", required = true) @RequestParam(defaultValue = "1") Integer page,
                                                        @ApiParam(value = "页码大小", required = true) @RequestParam(defaultValue = "20") Integer size) {
        if (0 > userId || page < 1 || size < 1) {
            return BusinessResult.createInstance(CommonResultMessage.PARMAS_INVALID);
        }
        try {
            userId = currentUserId();
            if (null == userId) {
                return BusinessResult.createInstance(CommonResultMessage.USER_NOT_LOGIN);
            }
            Page<UserDiaryZanVO> byTargetIdAndType = interactionMessageService.pageZanByZanedUserId(userId, page, size);
            return BusinessResult.createSuccessInstance(byTargetIdAndType);
        } catch (Exception ex) {
            log.error("", ex);
            return BusinessResult.createInstance(CommonResultMessage.DIARY_FAIL);
        }
    }

    @AutoLog(logLevel = DEBUG)
    @ApiOperation(value = "查询评论信息-转发后使用", notes = "查询评论信息-转发后使用")
    @GetMapping("/forward/Comment")
    @AuthSig
    public BusinessResult<ForwardCommentVO> forwardComment(@ApiParam(value = "评论id", required = true) @RequestParam Long commentId) {
        if (1 > commentId) {
            return BusinessResult.createInstance(CommonResultMessage.PARMAS_INVALID);
        }
        try {
            ForwardCommentVO forwardCommentVO = userDiaryReplyService.forwardCommentMyDiary(commentId);
            return BusinessResult.createSuccessInstance(forwardCommentVO);
        } catch (Exception ex) {
            log.error("forwar comment error ,ex = {}", ex);
            return BusinessResult.createInstance(CommonResultMessage.DIARY_FAIL);
        }
    }

    private String checkAddZan(UserDiaryZanDO userDiaryZan) {
        if (null == userDiaryZan) {
            return "请求体为空";
        } else if (null == userDiaryZan.getTargetId()) {
            return "目标id为空";
        } else if (null == UserDiaryZanDO.TypeEnums.create(userDiaryZan.getType())) {
            return "点赞类型错误";
        }
        return null;
    }


    private String checkAddReply(UserDiaryReplyDO userDiaryReply) {
        if (null == userDiaryReply) {
            return "请求体为空";
        } else if (StringUtils.isBlank(userDiaryReply.getReplyContent())) {
            return "回复内容为空";
        } else if (null == userDiaryReply.getReplyUserId()) {
            return "回复用户id为空";
        } else if (null == UserDiaryReplyDO.TypeEnums.create(userDiaryReply.getType())) {
            return "回复类型错误";
        } else if (null == userDiaryReply.getReplyedId() && UserDiaryReplyDO.TypeEnums.REPLY_REPLY == UserDiaryReplyDO.TypeEnums.create(userDiaryReply.getType())) {
            return "被回复的id为空";
        }
        return null;
    }

}
